package com.haizhi.crm.recommend.service.imp;

import com.haizhi.crm.common.constant.CrmSchema;
import com.haizhi.crm.common.json.JSONUtils;
import com.haizhi.crm.common.log.GLog;
import com.haizhi.crm.common.util.Getter;
import com.haizhi.crm.recommend.constant.RecType;
import com.haizhi.crm.recommend.model.RecQo;
import com.haizhi.crm.recommend.model.RecVo;
import com.haizhi.crm.recommend.service.RecService;
import com.haizhi.crm.search.builder.SearchQoBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyijun on 2018/7/6.
 */
@Service
public class InnerEventRelationSearch extends BaseRecService implements RecService {

    public static final GLog LOG = new GLog(InnerEventRelationSearch.class);

    @Override
    public String getName() {
        return RecType.InnerEvent.SEARCH_RELATION_SEARCH;
    }

    @Override
    public RecVo doRecommend(RecQo recQo) {
        try {
            String index = recQo.getGraph();
            SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
            searchQoBuilder.setGraph(index);
            searchQoBuilder.addSchemas(CrmSchema.EVENT_INNER);
            searchQoBuilder.addTermFilter("object_key", recQo.getVertexId());

            Object data = searchService.search(searchQoBuilder.get()).getSearchResp().getData();
            Map<String, Object> outerEvent = JSONUtils.toMap(data);
            String companyKey = Getter.get("customer_key", outerEvent);
            String type = Getter.get("type_", outerEvent);

            return getRecVo(recQo, index, companyKey, type);
        } catch (Exception e) {
            LOG.error("recommend inner event relation event error!", e);
            return (RecVo) new RecVo().setPayload(new ArrayList<>());
        }
    }

    private RecVo getRecVo(RecQo recQo, String index, String companyKey, String type) {
        SearchQoBuilder builder = new SearchQoBuilder();
        builder.setGraph(index);
        builder.addSchemas(CrmSchema.EVENT_INNER);
        builder.setPageSize(5);
        builder.setPageNo(1);
        builder.addTermFilter("type_", type);
        builder.addTermFilter("customer_key", companyKey);
        builder.addTermMustNotFilter("object_key", true, recQo.getVertexId());
        builder.addSort("event_time", "desc" );
        Object relationEvents = searchService.search(builder.get()).getSearchResp().getData();
        List<Map<String, Object>> relationEventMap = JSONUtils.toListMap(relationEvents);
        return (RecVo) new RecVo().setPayload(relationEventMap);
    }
}
